package top.market.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import top.market.constant.JwtConstants;
import top.market.model.entity.User;
import top.market.model.dto.LoginInfo;
import top.market.model.dto.UserLoginDTO;
import top.market.model.vo.Result;
import top.market.model.vo.UserVO;
import top.market.service.IUserService;
import top.market.util.CurrentUserUtil;
import top.market.util.JwtUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 微信小程序信息 前端控制器
 * </p>
 *
 * @author li yuhai
 * @since 2025-03-26
 */
@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService userService;

//    // 后台管理员登录入口
//    @PostMapping("/admin/login")
//    public Result login(@RequestBody LoginInfo loginInfo) {
//        User user = userService.findUserByUsernameAndPassword(loginInfo.getUsername(), loginInfo.getPassword());
//        if (!"ROLE_admin".equals(user.getRole())) {
//            return Result.create(403, "无权限");
//        }
//        user.setPassword(null);
//        String jwt = JwtUtils.generateToken(user.getUsername(), user.getId());
//        log.info(jwt);
////        String jwt = JwtUtils.generateToken(JwtConstants.ADMIN_PREFIX + user.getUsername());
//        Map<String, Object> map = new HashMap<>(4);
//        map.put("user", user);
//        map.put("token", jwt);
//        return Result.ok("登录成功", map);
//    }
//
    // 这里根据微信传入的code进行获取code，根据openid存储到数据库里面
    @PostMapping("/user/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        User user = userService.wxLogin(userLoginDTO);
        user.setPassword(null);
        String jwt = JwtUtils.generateToken(user.getUsername(), user.getId(), user.getAuthorities());
        Map<String, Object> map = new HashMap<>(4);
        map.put("user", user);
        map.put("token", jwt);
        return Result.ok("登录成功", map);
    }


    // 获取自己的账户基本信息
    @GetMapping("/user/info")
    public Result info() {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, CurrentUserUtil.getCustomUserDetails().getId());
        User user = userService.getOne(userWrapper);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.ok("获取成功", userVO);
    }

    
}
